package com.tungse.dynamic.service;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tungse.dynamic.domain.User;
import com.tungse.dynamic.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.util.Date;
import java.util.List;


@Service
public class UserService {

    @Autowired
    @Qualifier("masterDataSource")
    private DataSource masterDataSource;

    @Autowired
    @Qualifier("slaveDataSource")
    private DataSource slaveDataSource;

    @Autowired
    private UserMapper userMapper;


    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public User insertUser(User user) {
//        TransactionSynchronizationManager.getCurrentTransactionName()
//        extracted();

        userMapper.insert(user);
        UserService userService = SpringUtil.getBean(UserService.class);
        return userService.findUserById(user.getId());
    }


    public User findUserById(Integer id) {
//        extracted();
        return userMapper.selectById(id);
    }

//    @Transactional
    public List<User> selectUser(QueryWrapper<User> wrappers) {
//        extracted();
        List<User> users = userMapper.selectList(wrappers);

        UserService userService = SpringUtil.getBean(UserService.class);
        System.out.println("selectUser" + userService.insertUser(new User(null, "laoliu-009", "mmm", new Date())));

        return users;
    }

    private void extracted() {
        DataSourceTransactionManager txManager = SpringUtil.getBean(DataSourceTransactionManager.class);
        DataSource dataSource = txManager.getDataSource();
        System.out.println("当前线程的 dataSource = " + dataSource);
        System.out.println("masterDataSource = " + masterDataSource);
        System.out.println("slaveDataSource = " + slaveDataSource);
    }
}